package com.eightgroups.sys.controller;

import com.eightgroups.common.controller.BaseController;
import com.eightgroups.common.utils.DateUtil;
import com.eightgroups.common.utils.JsonMapUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.request.UploadFileRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class FileUploadController extends BaseController {

    private static final transient Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private COSClient cosClient;

    @Value("${file-upload-path}")
    private String fileUploadPath;
    @Value("${file-servler}")
    private Integer fileServler;

    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map<String, Object> upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("status", false);
        if (file.isEmpty()) {
            json.put("msg", "上传失败");
            return json;
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 获取年月
        int year = DateUtil.getYear();
        int month = DateUtil.getMonth();
        // 解决文件名重复问题 -- 解决中文问题，liunx下中文路径，图片显示问题
        String fileNameUUID = UUID.randomUUID() + suffixName;
        // 存放路径
        String path = "/" + year + "/" + month + "/";


        if (fileServler == 0) { // 本地
            //本地路径存放
            File dest = new File(fileUploadPath + path + fileNameUUID);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            // 存储文件
            try {
                file.transferTo(dest);
                json.put("fileType", 0);
                json.put("status", true);
                json.put("filePath", path + fileNameUUID );
                return json;
            } catch (IOException e) {
                json.put("msg", "上传失败");
                return json;
            }

        } else if (fileServler == 1) { //腾讯云
            try {
                // 获取字节留
                byte[] bytes = file.getBytes();
                // 上传文件并从腾讯云COS获取上传信息
                UploadFileRequest uploadFileRequest = new UploadFileRequest("cos",path + fileNameUUID, bytes);
                String result = cosClient.uploadSingleFile(uploadFileRequest);

                Map<String, String> cosMap = JsonMapUtil.parseToMap(result);
                Map<String, String> cosData = JsonMapUtil.parseToMap(cosMap.get("data"));
                if ("0".equals(cosMap.get("code"))) {
                    json.put("fileType", 1);
                    json.put("status", true);
                    json.put("filePath", cosData.get("source_url"));
                } else {
                    json.put("msg", "上传失败");
                }
                return json;
            } catch (IOException e) {
                json.put("msg", "上传失败");
                return json;
            }
        }
        json.put("msg", "上传失败");
        return json;
    }

    //文件下载相关代码
    @RequestMapping("/download")
    public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response) {
        String fileName = "code2.png";
        if (fileName != null) {
            File file = new File(fileUploadPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    //多文件上传
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }
}